package teacher;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.project.institute.DAO.InstituteListDAO;
import com.project.trac.R;

import core.modules.DatabaseConnector;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class MySchedules extends InstituteListDAO {

	private AlertDialog.Builder alertDialog_Builder;
	
	private final int CONTEXT_MENU_NEW_ACTIVITY = 1;
	private final int CONTEXT_MENU_NEW_THREAD = 2;
	private final int CONTEXT_MENU_EDIT_SCHEDULE = 3;
	private final int CONTEXT_MENU_DROP_SCHEDULE = 4;
	private final int CONTEXT_MENU_APPROVAL = 5;
	
	private int approval;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.teacher_my_schedules_list);
		setTitle("My Schedules");
		
		approval = getIntent().getExtras().getInt("TAG_APPROVAL");
		alertDialog_Builder = new AlertDialog.Builder(MySchedules.this);		
		
		
		
		getListView().setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> av, View view, int position, long id) {
				
				String item = av.getItemAtPosition(position).toString().replace("=", "");

				String SUBJECT_NAME = item.subSequence(item.indexOf("catalogNumber") + 13, item.indexOf(", curriculumID")).toString();
				String SUBJECT_ID = item.subSequence(item.indexOf("curriculumID") + 12, item.indexOf(", approval")).toString();
				String SCHEDULE_ID = item.subSequence(item.indexOf("scheduleID") + 10, item.indexOf(", code")).toString();
				
				setScheduleID(Integer.valueOf(SCHEDULE_ID));
				setSubjectName(SUBJECT_NAME);
				setSubjectID(Integer.valueOf(SUBJECT_ID));

				// To register the button with context menu.
				registerForContextMenu(av);
				openContextMenu(av);
			}
		});	
		
		new AsynchronousTask().execute("initialize");

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
		menu.setHeaderTitle("Select an Action");
		menu.add(Menu.NONE, CONTEXT_MENU_NEW_ACTIVITY, Menu.NONE, "New Activity");
		menu.add(Menu.NONE, CONTEXT_MENU_NEW_THREAD, Menu.NONE, "New Forum Topic");
		menu.add(Menu.NONE, CONTEXT_MENU_EDIT_SCHEDULE, Menu.NONE, "Edit Schedule");
		menu.add(Menu.NONE, CONTEXT_MENU_DROP_SCHEDULE, Menu.NONE, "Drop Schedule");
		menu.add(Menu.NONE, CONTEXT_MENU_APPROVAL, Menu.NONE, "Approval Request");		

	}

	@Override
	public void onContextMenuClosed(Menu menu) {
	    super.onContextMenuClosed(menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case CONTEXT_MENU_NEW_ACTIVITY:
			startActivity(new Intent(MySchedules.this, CreateActivity.class));
			break;

		case CONTEXT_MENU_NEW_THREAD:
			startActivity(new Intent(MySchedules.this, NewThread.class));
			break;

		case CONTEXT_MENU_EDIT_SCHEDULE:
			Toast.makeText(getApplicationContext(), "not yet implemented", Toast.LENGTH_SHORT).show();
			break;

		case CONTEXT_MENU_DROP_SCHEDULE:

			alertDialog_Builder.setTitle("Confirmation");
			alertDialog_Builder.setIcon(android.R.drawable.ic_dialog_alert);
			alertDialog_Builder.setMessage("Drop schedule for " + getSubjectName() + "?");

			alertDialog_Builder.setPositiveButton(android.R.string.ok,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {

							new AsynchronousTask().execute("drop");
							dialog.dismiss();
							
							// TODO: need to refresh list (1)
							getApplication().startActivity(getIntent());
						}
					});

			alertDialog_Builder.setNegativeButton(android.R.string.cancel,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.dismiss();
						}
					});

			break;
		case CONTEXT_MENU_APPROVAL:

			if (approval > 0) {
				startActivity(new Intent(MySchedules.this, Approvals.class));
			} else {
				Toast.makeText(getApplicationContext(), "no pending approvals",Toast.LENGTH_SHORT).show();
			}

			break;
		}

		return super.onContextItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.teacher, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.NEW_SCHEDULE:
			this.startActivity(new Intent(this, NewSchedule.class));
			break;
		default:
			return super.onOptionsItemSelected(item);
		}

		return true;
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}
	
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		Window window = getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}
	
	private class AsynchronousTask extends AsyncTask<String, String, String> {

		ProgressDialog progressDialog;
		
		HashMap<String, String> m;
		ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();

		ListAdapter listAdapter;
		
		ResultSet rs;

		String KEY_CAT = "catalogNumber";
		String KEY_SECTION = "section";
		String KEY_DAYS = "days";
		String KEY_TIME = "times";
		String KEY_ROOM = "rooms";
		String KEY_REGISTRATION_CODE = "code";
		String KEY_STUDENTS = "max";
		String KEY_CURRICULUM_ID = "curriculumID";
		String KEY_SCHEDULE_ID = "scheduleID";
		String KEY_APPROVAL = "approval";

		protected void onPreExecute() {
			super.onPreExecute();

			progressDialog = new ProgressDialog(MySchedules.this);
			progressDialog.setMessage("please wait...");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(true);
			progressDialog.show();
		}

		protected String doInBackground(String... args) {

			try {
				
				if (args[0].equalsIgnoreCase("initialize")) {
					 rs = DatabaseConnector.getStatement().executeQuery(
							"SELECT schedule.id, schedule.cid, curriculum.catalognumber, schedule.section, "
							+ " schedule.room, schedule.days, schedule.time, schedule.code, schedule.max, "
							+ " (SELECT COUNT(gradesheet.id) FROM gradesheet "
							+ " WHERE gradesheet.sid = schedule.id) AS 'enrolled', "
							+ " (SELECT COUNT(gradesheet.id) FROM gradesheet "
							+ " WHERE gradesheet.sid = schedule.id AND gradesheet.isApproved = 0) AS 'approval' "
							+ " FROM schedule "
							+ " INNER JOIN curriculum ON curriculum.id = schedule.cid "
							+ " WHERE schedule.uid = " + getUserID());

					while (rs.next()) {

						m = new HashMap<String, String>();
						m.put(KEY_CAT, rs.getString("catalognumber"));
						m.put(KEY_STUDENTS, rs.getString("enrolled") + "/" + rs.getString("max"));
						m.put(KEY_SECTION, rs.getString("section"));
						m.put(KEY_DAYS, rs.getString("days"));
						m.put(KEY_TIME, rs.getString("time"));
						m.put(KEY_ROOM, rs.getString("room"));
						m.put(KEY_REGISTRATION_CODE, rs.getString("code"));
						m.put(KEY_CURRICULUM_ID, rs.getString("cid"));
						m.put(KEY_SCHEDULE_ID, rs.getString("schedule.id"));
						m.put(KEY_APPROVAL, rs.getString("approval"));

						arrayList.add(m);

					}
					
					rs.close();
					
				} else if (args[0].equalsIgnoreCase("drop")) {
					DatabaseConnector.getConnection().setAutoCommit(false);
					PreparedStatement pps = DatabaseConnector.getConnection().prepareStatement("DELETE FROM schedule WHERE id = ? AND uid = ? AND cid = ?");
					
					pps.setInt(1, getScheduleID());		
					pps.setInt(2, getUserID());		
					pps.setInt(3, getSubjectID());

					pps.executeUpdate();			
					pps.clearParameters();			
					pps.close();
				}

			} catch (SQLException e) {
				DatabaseConnector.Logger(getClass(), "doInBackground", e);
			}

			return null;
		}

		protected void onPostExecute(String postExecute) {

			progressDialog.dismiss();

			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					listAdapter = new SimpleAdapter(
							MySchedules.this, arrayList, R.layout.teacher_subjects_view,
							new String[] { KEY_CAT, KEY_STUDENTS, KEY_SECTION, KEY_DAYS, KEY_TIME, KEY_ROOM, KEY_REGISTRATION_CODE, KEY_APPROVAL },
							new int[] { R.id.r_key_cat_new, R.id.tv_students, R.id.section, R.id.days, R.id.time, R.id.room, R.id.code, R.id.tv_approval });

					setListAdapter(listAdapter);
				}
			});
		}
	}

}